﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Collections;
using System.Configuration;
namespace gamexpert
{
    public partial class PurchaseGames : System.Web.UI.Page
    {
        DataSet globalds;
        protected void Page_Load(object sender, EventArgs e)
        {
            purchaseViewType pvt=getViewType();
            DataSet ds = null ;
            switch(pvt){
                case purchaseViewType.ViewAccessories:
                    MultiView1.ActiveViewIndex = 0;
                    ds = DataBroker.getProductsByCat("Accessories");
                    Literal1.Text = "Purchase Accessories";
                    break;
                case purchaseViewType.ViewBoth:
                    MultiView1.ActiveViewIndex = 0;
                    ds = DataBroker.getAllProducts();
                    Literal1.Text = "Purchase";
                    break;
                case purchaseViewType.ViewDetail:
                    /*
                    MultiView1.ActiveViewIndex = 1;
                    ds = DataBroker.getProductById(id);
                     * */
                    if (Request["cat"] != null && (Request["cat"] == "Games" || Request["cat"]=="Accessories"))
                    {
                        ds = DataBroker.getProductsByCat(Request["cat"]);
                    }else{
                        ds = DataBroker.getAllProducts();
                    }
                    int id = Int32.Parse(Request["id"]);
                    DataSet dss = DataBroker.getProductById(id);
                    FormView1.DataSource = dss;
                    FormView1.DataBind();
                    if (!IsPostBack)
                    {
                        MultiView1.ActiveViewIndex = 1;
                    }
                    
                    break;
                case purchaseViewType.ViewGames:
                    MultiView1.ActiveViewIndex = 0;
                    ds = DataBroker.getProductsByCat("Games");
                    Literal1.Text = "Purchase Games";
                    break;
                case purchaseViewType.ViewSearch:
                    MultiView1.ActiveViewIndex = 0;
                    string keyword = Request["search"];
                    if (keyword == "" || keyword==null)
                    {
                        keyword = "a";
                    }
                    ds = DataBroker.searchProducts(keyword);
                    Literal1.Text = "Search Results";
                    break;
            }
            globalds=ds;
            if (!IsPostBack)
            {
                bindData();
            }
            else
            {
                //since the pagination controls are dynamically creating its shld be re created in each page load
                BuildPagination();
            }

        }
        purchaseViewType getViewType()
        {
            purchaseViewType pvt = purchaseViewType.ViewNone;
            if (Request["search"] != null)
            {
                pvt = purchaseViewType.ViewSearch;
            }
            else if (Request["id"] != null)
            {
                pvt = purchaseViewType.ViewDetail;
            }
            else if (Request["cat"] != null && Request["cat"] == "Games")
            {
                pvt = purchaseViewType.ViewGames;
            }
            else if (Request["cat"] != null && Request["cat"] == "Accessories")
            {
                pvt = purchaseViewType.ViewAccessories;
            }
            else
            {
                pvt = purchaseViewType.ViewBoth;
            }
            return pvt;
        }
        private void bindData()
        {
            bindDataWithPaging(DataList1, globalds);
        }
        protected void DataList1_SelectedIndexChanged(object sender, EventArgs e)
        {
            DataSet ds = DataBroker.getProductById((int)DataList1.SelectedValue);
            FormView1.DataSource = ds;
            FormView1.DataBind();
            MultiView1.ActiveViewIndex = 1;
        }

        protected void FormView1_ItemCommand(object sender, FormViewCommandEventArgs e)
        {
            if (e.CommandName == "Back")
            {
                MultiView1.ActiveViewIndex = 0;
            }
            else if (e.CommandName == "AddToCart")
            {
                addtocart(Int32.Parse(e.CommandArgument.ToString()));
            }
        }
        void addtocart(int id)
        {
            Cart c = (Cart)Session["cart"];
            Product p = new Product(id, 1);
            c.AddProduct(p);
            Session["cart"] = c;
            MultiView1.ActiveViewIndex = 2;
            Literal literalCtrl = ((Literal)Master.FindControl("Literal1"));
        }
        protected void DataList1_ItemCommand(object source, DataListCommandEventArgs e)
        {
            if (e.CommandName == "AddToCart")
            {
                addtocart(Int32.Parse(e.CommandArgument.ToString()));
            }
        }


        protected void lbtnContinueShop_Click(object sender, EventArgs e)
        {
            MultiView1.ActiveViewIndex = 0;

        }
        protected void lbtnViewCart_Click(object sender, EventArgs e)
        {
            Response.Redirect("ShoppingCart.aspx");
        }
        protected void lbtnCart_Click(object sender, EventArgs e)
        {
            Response.Redirect("ShoppingCart.aspx");
        }
        #region Pager Creation
        protected void lnkPager_Click(object sender, EventArgs e) //Page index changed function
        {
            LinkButton lnk = (LinkButton)sender;
            CurrentPageIndex = int.Parse(lnk.CommandArgument);

            bindData();
        }

        private int PageSize //total rows per page
        {
            get { return 5; }
        }

        private int ButtonsCount //how many total linkbuttons shld be shown
        {
            get { return 9; }
        }

        private string FirstPageText
        {
            get { return "&lt;&lt;"; }
        }
        private string LastPageText
        {
            get { return "&gt;&gt;"; }
        }
        private string PreviousPageText
        {
            get { return "&lt;"; }
        }
        private string NextPageText
        {
            get { return "&gt;"; }
        }

        private void bindDataWithPaging(Control bindControl, DataSet data) //you can pass either DatList or Repeater to this function
        {
            if (data.Tables.Count > 0) // if the datset contains data
            {
                DataView dv = data.Tables[0].DefaultView;

                PagedDataSource dsP = new PagedDataSource();
                dsP.AllowPaging = true;
                dsP.DataSource = dv;
                dsP.CurrentPageIndex = CurrentPageIndex;
                dsP.PageSize = PageSize;

                //Binding data to the controls
                if (bindControl is DataList)
                {
                    ((DataList)bindControl).DataSource = dsP;
                    ((DataList)bindControl).DataBind();
                }
                else if (bindControl is Repeater)
                {
                    ((Repeater)bindControl).DataSource = dsP;
                    ((Repeater)bindControl).DataBind();
                }

                //saving the total page count in Viewstate for later use
                PageCount = dsP.PageCount;

                //create the linkbuttons for pagination
                BuildPagination();
            }
        }

        private int CurrentPageIndex //to store the current page index
        {
            get { return ViewState["CurrentPageIndex"] == null ? 0 : int.Parse(ViewState["CurrentPageIndex"].ToString()); }
            set { ViewState["CurrentPageIndex"] = value; }
        }
        private int PageCount  //total number of pages needed to display the data
        {
            get { return ViewState["PageCount"] == null ? 0 : int.Parse(ViewState["PageCount"].ToString()); }
            set { ViewState["PageCount"] = value; }
        }

        private LinkButton createButton(string title, int index)
        {
            LinkButton lnk = new LinkButton();
            lnk.ID = index.ToString();
            lnk.Text = title;
            lnk.CommandArgument = index.ToString();
            lnk.Click += new EventHandler(lnkPager_Click);
            lnk.CssClass = "paginglnk";
            return lnk;
        }

        //create the linkbuttons for pagination
        protected void BuildPagination()
        {
            pnlPager.Controls.Clear(); //

            if (PageCount <= 1) return; // at least two pages should be there to show the pagination

            //finding the first linkbutton to be shown in the current display
            int start = CurrentPageIndex - (CurrentPageIndex % ButtonsCount);

            //finding the last linkbutton to be shown in the current display
            int end = CurrentPageIndex + (ButtonsCount - (CurrentPageIndex % ButtonsCount));

            //if the start button is more than the number of buttons. If the start button is 11 we have to show the <<First link
            if (start > ButtonsCount - 1)
            {
                pnlPager.Controls.Add(createButton(FirstPageText, 0));
                pnlPager.Controls.Add(createButton(PreviousPageText, start - 1));
            }

            int i = 0, j = 0;

            for (i = start; i < end; i++)
            {
                LinkButton lnk;
                if (i < PageCount)
                {
                    if (i == CurrentPageIndex) //if its the current page
                    {
                        Label lbl = new Label();
                        lbl.Text = (i + 1).ToString();
                        pnlPager.Controls.Add(lbl);
                    }
                    else
                    {
                        pnlPager.Controls.Add(createButton((i + 1).ToString(), i));
                    }
                }
                j++;
            }

            //If the total number of pages are greaer than the end page we have to show Last>> link
            if (PageCount > end)
            {
                pnlPager.Controls.Add(createButton(NextPageText, i));
                pnlPager.Controls.Add(createButton(LastPageText, PageCount - 1));
            }
            
        }
        
        #endregion

        
    }
}
